﻿using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using System.Windows.Controls;

namespace LightSwitchApplication
{
    public partial class PatientDetail
    {
        partial void Patient_Loaded(bool succeeded)
        {
            // Write your code here.
            this.SetDisplayNameFromEntity(this.Patient);
        }

        partial void Patient_Changed()
        {
            // Write your code here.
            this.SetDisplayNameFromEntity(this.Patient);
        }

        partial void PatientDetail_Saved()
        {
            // Write your code here.
            this.SetDisplayNameFromEntity(this.Patient);
        }

        partial void PatientDetail_InitializeDataWorkspace(List<IDataService> saveChangesTo)
        {
            // Write your code here.
            Icon_Expired = LightSwitchApplication.UserCode.MyImageHelper.GetImageByName("history.png");
            Icon_Fillable = LightSwitchApplication.UserCode.MyImageHelper.GetImageByName("fillable.png");
            Icon_InTaking = LightSwitchApplication.UserCode.MyImageHelper.GetImageByName("inuse.png");

            Text_Expired = "Prescriptions Expired";
            Text_Fillable = "Prescriptions Fillable";
            Text_InTaking = "Prescriptions in Taking";
        }

        partial void PatientDetail_Created()
        {
            // Write your code here.
            this.FindControl("NewPrescription").ControlAvailable += (sender, args) =>
            {
                ChildWindow dialog = args.Control as ChildWindow;
                dialog.Closed += (s, a) => { if (!dialog.DialogResult.HasValue || dialog.DialogResult == false) NewPrescription.Details.DiscardChanges(); };
            };

            this.NumOfPrescriptionFillable = this.DataWorkspace.ApplicationData.PrescriptionsFillable(PatientId).Cast<Prescription>().Count();
            this.NumOfPrescriptionsExpired = this.DataWorkspace.ApplicationData.PrescriptionsExpired(PatientId).Cast<Prescription>().Count();
            this.NumOfPrescriptionInTaking = this.DataWorkspace.ApplicationData.PrescriptionsInTaking(PatientId).Cast<Prescription>().Count();
        }

        partial void showFillable_CanExecute(ref bool result)
        {
            // Write your code here.
            //result = this.NumOfPrescriptionFillable > 0;
        }

        partial void showFillable_Execute()
        {
            // Write your code here.
            this.Application.ShowPrescriptionsFillableListDetail(this.PatientId);
        }

        partial void showInTaking_CanExecute(ref bool result)
        {
            // Write your code here.
            result = this.NumOfPrescriptionInTaking > 0;
        }

        partial void showInTaking_Execute()
        {
            // Write your code here.
            this.Application.ShowPrescriptionsInTakingListDetail(this.PatientId);
        }

        partial void showExpired_CanExecute(ref bool result)
        {
            // Write your code here.
            result = this.NumOfPrescriptionsExpired > 0;
        }

        partial void showExpired_Execute()
        {
            // Write your code here.
            this.Application.ShowPrescriptionsExpiredListDetail(this.PatientId);
        }

        partial void Ok_Execute()
        {
            // Write your code here.
            this.CloseModalWindow("NewPrescription");
        }

        partial void Cancel_Execute()
        {
            // Write your code here.
            this.CloseModalWindow("NewPrescription");
            NewPrescription.Details.DiscardChanges();
        }

        partial void AddPrescription_Execute()
        {
            // Write your code here.
            NewPrescription = this.DataWorkspace.ApplicationData.Prescriptions.AddNew();
            NewPrescription.Customer = this.Patient;
            NewPrescription.Dosage = 1;
            NewPrescription.TakingWeeks = 1;
            NewPrescription.TakingTimesPerDay = 1;
            NewPrescription.Refills = 0;
            this.OpenModalWindow("NewPrescription");
        }


        /*

        partial void PrescriptionsEditSelected_CanExecute(ref bool result)
        {
            // Write your code here.
            if (this.Prescriptions.SelectedItem != null)
                result = this.Prescriptions.SelectedItem.Id == 0;
            else
                result = false;

        }

        partial void PrescriptionsEditSelected_Execute()
        {
            // Write your code here.
            this.Prescriptions.EditSelected();
        }

        partial void PrescriptionsDeleteSelected_CanExecute(ref bool result)
        {
            // Write your code here.
            if (this.Prescriptions.SelectedItem != null)
                result = this.Prescriptions.SelectedItem.Id == 0;
            else
                result = false;
        }

        partial void PrescriptionsDeleteSelected_Execute()
        {
            // Write your code here.
            this.Prescriptions.DeleteSelected();
        }


        partial void FillPrescriptions_Execute()
        {
            // Write your code here.
            this.Application.ShowPrescriptionsFillableForPatientListDetail(this.PatientId);
        }

        private String FormatName(String name)
        {
            if(name != null)
                return name.TrimStart().Substring(0, 1).ToUpper() + name.TrimEnd().Substring(1).ToLower();
            return "";
        }
        
        private void updatePhysicianList()
        {
            foreach (AdminData data in this.DataWorkspace.ApplicationData.AdminDatas)
            {
                String phFirstName = FormatName(data.PhysicianFirstName);
                String phLastName = FormatName(data.PhysicianLastName);
                String phPhone = data.PhysicianPhone.Trim();
                Physician physician = this.DataWorkspace.ApplicationData.Physicians.Where(physicians =>
                    physicians.FirstName == phFirstName && physicians.LastName == phLastName &&
                    physicians.Phone == phPhone).FirstOrDefault();
                if (physician == null)
                {
                    Physician newPhysician = new Physician();
                    newPhysician.FirstName = phFirstName;
                    newPhysician.LastName = phLastName;
                    newPhysician.Phone = phPhone;
                }
            }
            if (this.CanSave)
                this.Save();
        }


        partial void LoadEMRData_CanExecute(ref bool result)
        {
            // Write your code here.
            String fName = this.Patient.FirstName;
            String lName = this.Patient.LastName;
            DateTime dob = this.Patient.DOB; 
            result = this.DataWorkspace.ApplicationData.EmrDatas.Where(emrs =>
                    emrs.PatientFirstName == fName && emrs.PatientLastName == lName &&
                    emrs.PatientDOB == dob).FirstOrDefault() != null;
        }

        partial void LoadEMRData_Execute()
        {
            // Write your code here.
            updatePhysicianList();
            foreach (EmrData data in this.DataWorkspace.ApplicationData.EmrDatas.Where(emrs =>
                emrs.PatientFirstName == this.Patient.FirstName && emrs.PatientLastName == this.Patient.LastName &&
                emrs.PatientDOB == this.Patient.DOB && emrs.Status == null))
            {
                this.Prescriptions.AddNew();
                this.Prescriptions.SelectedItem.MedicalName = data.MedicalName;
                this.Prescriptions.SelectedItem.Patient = this.Patient;
                this.Prescriptions.SelectedItem.Refills = data.Refills;
                this.Prescriptions.SelectedItem.TakingDays = data.TakingDays;
                this.Prescriptions.SelectedItem.TakingTimesPerDay = data.TakingTimesPerDay;
                this.Prescriptions.SelectedItem.Dosage = data.Dosage;
                this.Prescriptions.SelectedItem.CommercialName = data.CommercialName;
                this.Prescriptions.SelectedItem.CreatedTime = data.CreatedTime;
                this.Prescriptions.SelectedItem.IsTakenWithFood = data.isTakenWithFood;

                String phFirstName = FormatName(data.PhysicianFirstName);
                String phLastName = FormatName(data.PhysicianLastName);
                this.Prescriptions.SelectedItem.Physician = this.DataWorkspace.ApplicationData.Physicians.Where(physicians =>
                    physicians.FirstName == phFirstName && physicians.LastName == phLastName &&
                    physicians.Phone == data.PhysicianPhone.Trim() && physicians.Id != 0).FirstOrDefault(); //WHY?

                if (this.Prescriptions.SelectedItem.MedicalName == null && this.Prescriptions.SelectedItem.CommercialName == null)
                    data.Status += "Both of the medical name and commercial name are empty.";
                if (this.Prescriptions.SelectedItem.Physician == null)
                    data.Status += "The physician is not in the name list for the prescription-drugs";

                if (data.Status != null)
                    this.Prescriptions.SelectedItem.Delete();         
            }
        }

        partial void PatientDetail_InitializeDataWorkspace(List<IDataService> saveChangesTo)
        {
        // Write your code here.

        }

        partial void PrescriptionsAddAndEditNew_CanExecute(ref bool result)
        {
            // Write your code here.

        }

        partial void PrescriptionsAddAndEditNew_Execute()
        {
            // Write your code here.
            updatePhysicianList();
            this.Prescriptions.AddAndEditNew();
        }

        partial void FillPrescriptions_CanExecute(ref bool result)
        {
            // Write your code here.
            result = this.DataWorkspace.ApplicationData.PrescriptionsFillableForPatient(PatientId).FirstOrDefault() != null;
        }

        partial void InUse_Execute()
        {
            // Write your code here.
            this.Application.ShowSearchPrescriptionsInUseForPatient(this.PatientId);
        }*/
    }
}